package com.wwg.myapplication;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Build;
import android.os.IBinder;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Surface;
import android.view.SurfaceControl;
import android.view.WindowManager;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

public class BitmapUtils {
    private static final String TAG = "BitmapUtils";

    public static Bitmap getBitmap(Context context) {
        // 1. 优先尝试现代API（Android 12+）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            Bitmap result = getBitmapModern(context);
            if (result != null) {
                return result;
            }
            Log.w(TAG, "Modern screenshot failed, falling back to legacy method");
        }

        // 2. 尝试旧版API（Android 5-11）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Bitmap result = getBitmapLegacy(context);
            if (result != null) {
                return result;
            }
            Log.w(TAG, "Legacy screenshot failed, falling back to fallback method");
        }

        // 3. 终极回退方案
        return getBitmapFallback(context);
    }

    /**
     * 现代截图方法（Android 12+）
     */
    private static Bitmap getBitmapModern(Context context) {
        try {
            // 检查所需类是否可用
            if (!isClassAvailable("android.view.SurfaceControl$DisplayCaptureArgs")) {
                Log.e(TAG, "Required classes not available for modern screenshot");
                return null;
            }

            Class<?> surfaceControlClass = Class.forName("android.view.SurfaceControl");
            Class<?> displayCaptureArgsClass = Class.forName("android.view.SurfaceControl$DisplayCaptureArgs");
            Class<?> builderClass = Class.forName("android.view.SurfaceControl$DisplayCaptureArgs$Builder");

            // 获取显示令牌
            Method getInternalDisplayToken = surfaceControlClass.getMethod("getInternalDisplayToken");
            IBinder displayToken = (IBinder) getInternalDisplayToken.invoke(null);

            // 构建截图参数
            Constructor<?> builderConstructor = builderClass.getConstructor(IBinder.class);
            Object builder = builderConstructor.newInstance(displayToken);

            // 设置截图区域（全屏）
            WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            Display display = wm.getDefaultDisplay();
            Point size = new Point();
            display.getRealSize(size);

            // 确保尺寸有效
            if (size.x <= 0 || size.y <= 0) {
                Log.e(TAG, "Invalid screen size: " + size.x + "x" + size.y);
                return null;
            }

            Method setSize = builderClass.getMethod("setSize", int.class, int.class);
            setSize.invoke(builder, size.x, size.y);

            // 构建参数对象
            Method buildMethod = builderClass.getMethod("build");
            Object captureArgs = buildMethod.invoke(builder);

            // 执行截图
            Method captureDisplay = surfaceControlClass.getMethod("captureDisplay", displayCaptureArgsClass);
            Object hardwareBuffer = captureDisplay.invoke(null, captureArgs);

            // 转换为Bitmap
            Class<?> hardwareBufferClass = Class.forName("android.hardware.HardwareBuffer");
            Method asBitmap = hardwareBufferClass.getMethod("asBitmap");
            return (Bitmap) asBitmap.invoke(hardwareBuffer);
        } catch (Throwable e) {
            Log.e(TAG, "Modern screenshot failed", e);
            return null;
        }
    }

    /**
     * 检查类是否可用
     */
    private static boolean isClassAvailable(String className) {
        try {
            Class.forName(className);
            return true;
        } catch (ClassNotFoundException e) {
            return false;
        }
    }

    /**
     * 旧版截图方法（Android 5-11）
     */
    private static Bitmap getBitmapLegacy(Context context) {
        try {
            Class<?> surfaceControlClass = Class.forName("android.view.SurfaceControl");
            Method screenshotMethod = null;

            // 尝试不同参数组合的方法签名
            try {
                // Android 10+ 签名
                screenshotMethod = surfaceControlClass.getMethod(
                        "screenshot",
                        Rect.class,
                        int.class,
                        int.class,
                        int.class
                );
            } catch (NoSuchMethodException e) {
                // Android 5-9 签名
                screenshotMethod = surfaceControlClass.getMethod(
                        "screenshot",
                        int.class,
                        int.class
                );
            }

            WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            Display display = wm.getDefaultDisplay();
            Point size = new Point();
            display.getRealSize(size);

            // 确保尺寸有效
            if (size.x <= 0 || size.y <= 0) {
                Log.e(TAG, "Invalid screen size: " + size.x + "x" + size.y);
                return null;
            }

            if (screenshotMethod.getParameterTypes().length == 4) {
                // 使用新签名: screenshot(Rect, width, height, rotation)
                return (Bitmap) screenshotMethod.invoke(
                        null,
                        new Rect(0, 0, size.x, size.y), // 截图区域
                        size.x,                          // 宽度
                        size.y,                          // 高度
                        0                                // 旋转
                );
            } else {
                // 使用旧签名: screenshot(width, height)
                return (Bitmap) screenshotMethod.invoke(
                        null,
                        size.x, // 宽度
                        size.y  // 高度
                );
            }
        } catch (Throwable e) {
            Log.e(TAG, "Legacy screenshot failed", e);
            return null;
        }
    }

    /**
     * 回退方案：创建纯色位图
     */
    private static Bitmap getBitmapFallback(Context context) {
        int width = 1920;
        int height = 1080;

        try {
            // 尝试获取实际屏幕尺寸
            WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            if (wm != null) {
                Display display = wm.getDefaultDisplay();
                Point size = new Point();
                display.getRealSize(size);

                if (size.x > 0 && size.y > 0) {
                    width = size.x;
                    height = size.y;
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "Error getting display size", e);
        }

        // 确保最小尺寸
        if (width <= 0) width = 1920;
        if (height <= 0) height = 1080;

        try {
            // 创建渐变背景
            Bitmap bitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);

            // 创建蓝色渐变背景
            Paint paint = new Paint();
            paint.setShader(new android.graphics.LinearGradient(
                    0, 0, width, height,
                    Color.rgb(0, 100, 200), Color.rgb(100, 0, 200),
                    android.graphics.Shader.TileMode.CLAMP));
            canvas.drawRect(0, 0, width, height, paint);

            // 添加调试信息
            paint.setShader(null);
            paint.setColor(Color.WHITE);
            paint.setTextSize(100);
            paint.setTextAlign(Paint.Align.CENTER);

            String text1 = "Screenshot Failed";
            String text2 = "Using Fallback Bitmap";
            String text3 = "Size: " + width + "x" + height;

            canvas.drawText(text1, width/2, height/2 - 200, paint);
            canvas.drawText(text2, width/2, height/2, paint);
            canvas.drawText(text3, width/2, height/2 + 200, paint);

            return bitmap;
        } catch (Exception e) {
            Log.e(TAG, "Fallback bitmap creation failed", e);

            // 终极回退：纯色位图
            return Bitmap.createBitmap(width, height, Config.ARGB_8888);
        }
    }

    // 内部Point类（如果未导入）
    private static class Point extends android.graphics.Point {
        int x, y;
    }
}